package com.okaixz.framework.utils;

import com.alibaba.fastjson2.JSON;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class CommonUtils {
    /**
     * 向客户端返回 JSON 字符串
     * @param response HttpServletResponse 对象
     * @param jsonStr 要返回的 com.alibaba.fastjson2.JSON 格式字符串
     */
    public static void writeJson(HttpServletResponse response, String jsonStr,Integer statusCode) {
        // 1. 设置响应内容类型为 JSON，字符编码为 UTF-8
        response.setContentType("application/json;charset=UTF-8");
        // 2. 禁用缓存（可选，根据业务需求）
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        if (statusCode != null) {
            response.setStatus(statusCode);
        }

        try (PrintWriter out = response.getWriter()) { // 3. 获取输出流（try-with-resources 自动关闭）
            // 4. 写入 JSON 字符串
            out.write(jsonStr);
            // 5. 刷新输出流，确保数据发送到客户端
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
